package cn.org.gs.selector;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorDemo1 {

    @Test
    public void a() throws Exception{
        // 1、获取Selector选择器
        Selector selector = Selector.open();
        // 2、获取通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        // 3、设置为非阻塞
        socketChannel.configureBlocking(false);
        // 4、绑定连接
        socketChannel.bind(new InetSocketAddress(9999));
        // 5、将通道注册到选择器上，并制定监听事件为：“接收”事件
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 查询已经就绪通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        // 遍历
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            // 判断可以就绪状态操作
            if (key.isAcceptable()) {

            } else if(key.isConnectable()) {

            } else if (key.isReadable()) {

            } else if (key.isWritable()) {

            }

            iterator.remove();
        }
    }
}
